package com.hmz.backend.controller.account;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmz.backend.consumer.WebSocketServer;
import com.hmz.backend.entity.User;
import com.hmz.backend.entity.Message;
import com.hmz.backend.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
public class UpLoadFileController {
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${my-server-address}")
    private String myServerAddress;
    @Value("${avatar-path}")
    private   String avatarPath ; //存放头像的路径
    @Value("${message-img-path}")
    private  String messageImgPath; //存放信息中的图片的路径
    @Value("${get-avatar-path}")
    private String getAvatarPath; //用户头像存放的基础地址
    @Autowired
    UserMapper userMapper;

    /**
     * 上传图片
     * @param file
     * @param userId
     * @return
     */
    @RequestMapping("/uploadAvatar/{userId}")
    public JSONObject upLoadAvatar(MultipartFile file, @PathVariable int userId) {
        if(file.isEmpty()){
            return new JSONObject().set("message","文件上传失败，请选择文件");
        }
        try {
            //创建一个专门存放用户头像的文件夹
            File dir = new File(avatarPath);
            //如果这个文件夹不存在的话，就创建这个文件夹
            if(!dir.exists())  dir.mkdir();
            //获取文件原名
            String fileName = file.getOriginalFilename();
            //获取文件后缀名
            String fileExtension = fileName.substring(fileName.indexOf("."));
            //通过FileOutputStream保存文件 ，路径为存储头像的路径(/.../)+用户Id+"_avatar."+用户上传文件的原后缀名
            FileOutputStream fileOutputStream = new FileOutputStream(avatarPath+"user"+userId+"_avatar"+fileExtension);
            //获取用户上传文件的所有字节
            byte[] bytes = file.getBytes();
            //通过文件字节输出流将所有字节写入到对应路径
            fileOutputStream.write(bytes);
            //刷新文件字节输出流的缓冲区,强制写入到路径中
            fileOutputStream.flush();
            //关闭文件字节输出流
            fileOutputStream.close();
            //将对应的用户修改其头像字段
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            User user = userMapper.selectOne(queryWrapper);
            user.setAvatar(myServerAddress+getAvatarPath+"/user"+userId+"_avatar"+fileExtension);
            userMapper.update(user,queryWrapper);
            return new JSONObject().set("message","文件上传成功");
        } catch (IOException e) {
            System.out.println(e);
            return new JSONObject().set("message","文件上传失败");
        }

    }
    /**
     * 发送图片的消息
     * @param file
     * @param userId
     * @param chatRoomId
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadImage/{userId}/{chatRoomId}")
    public JSONObject uploadImage(MultipartFile file,@PathVariable int userId,@PathVariable int chatRoomId) throws IOException {
        //如果目录不存在，自动创建文件夹
        File messageImgDir = new File(messageImgPath);
        if(!messageImgDir.exists())  messageImgDir.mkdir();
        Date date = new Date();//获取当前的日期
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String timeStamp = df.format(date);//获取String类型的时间戳
        String fileName = file.getOriginalFilename();     //获取文件原名
        String fileExtension = fileName.substring(fileName.indexOf("."));  //获取文件后缀名
        FileOutputStream fileOutputStream = new FileOutputStream(messageImgPath+"chatRoom"+chatRoomId+timeStamp+fileExtension);
        byte[] bytes = file.getBytes();
        fileOutputStream.write(bytes); //保存文件
        fileOutputStream.flush(); //刷新缓冲区
        fileOutputStream.close(); //关闭输出流
        Message message = new Message(0,userId,chatRoomId,"chatRoom"+chatRoomId+timeStamp+fileExtension,1,date);
        redisTemplate.opsForList().rightPush("message"+chatRoomId,message);
        WebSocketServer.sendMessage(message);
        return new JSONObject().set("message","上传图片成功");
    }
//        字节数组输出流
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        压缩图片并写入输出流
//        Thumbnails.of(file.getInputStream()).size(100,100).toOutputStream(byteArrayOutputStream);
//        转成base64字符串
//        String imageBase64 = Base64.encodeBase64String(file.getBytes());
}
